package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import(MybatisConfig.class)
//@EnableAspectJAutoProxy//开启事务注解支持
@EnableTransactionManagement//开启事务管理，开启对事务注解的支持
public class SpringConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource getDataSource(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    /**
     * 定义事务管理器的bean
     * @param dataSource
     * @return
     * 事务管理器的名称最好叫：transactionManager
     * 因为早起使用xml开发时，xml中引用的事务管理器的bean在xml的约束中写死，就叫做transactionManager
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        //支持mybatis spring-jdbc组件事务管理
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}
